package com.zx.disneyholidays.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.zx.disneyholidays.BuildConfig;
import com.zx.disneyholidays.MyApplication;

import java.io.File;


/**
 * Created by xiewei on 2018/1/25.
 */

public class MediaUtils {
    public static final int ACTION_FROM_ALBUM = 10002;
    public static final int ACTION_FROM_CAMERA = 10001;
    public static final int ACTION_FROM_CROP = 10003;
    public static final int ACTION_FROM_MODIFY_NAME = 10004;
    public static final int ACTION_FROM_MODIFY_TELE_NUMBER = 10005;
    public static final int ACTION_FROM_MODIFY_REMARK = 10006;

    public static final String JPEG_FILE_SUFFIX = ".jpg";


    public static void getFromCrop(Fragment fragment, Uri source, File output) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (source == null) {
            Toast.makeText(fragment.getContext(), "裁剪的图片不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            intent.setDataAndType(source, "image/*");
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 800);
            intent.putExtra("outputY", 800);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            fragment.startActivityForResult(intent, ACTION_FROM_CROP);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void getFromCrop(Activity activity, Uri source, File output) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (source == null) {
            Toast.makeText(activity, "裁剪的图片不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            source = replaceUriFromPickImage(activity, source);
            intent.setDataAndType(source, "image/*");
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 800);
            intent.putExtra("outputY", 800);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fromFile(output));
            intent.putExtra("return-data", false);
            intent.putExtra("scale", true);
            intent.putExtra("scaleUpIfNeeded", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            setIntentForCameraCrop(intent);
            activity.startActivityForResult(intent, ACTION_FROM_CROP);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Uri replaceUriFromPickImage(Context context, Uri uri) {
        if (Build.VERSION.SDK_INT >= 24) {
            try {
                if (uri != null && uri.getScheme() != null &&
                        uri.getScheme().contains("content")) {
                    try {
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = context.getContentResolver().query(uri,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        if (cursor != null) {
                            cursor.moveToFirst();
                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            String picturePath = cursor.getString(columnIndex);  //获取照片路径
                            cursor.close();
                            if (picturePath != null) {
                                File file = new File(picturePath);
                                return fromFileFor24(context, file);
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else if (uri != null && uri.getScheme() != null &&
                        uri.getScheme().contains("file")) {
                    if (uri.getPath() != null) {
                        File file = new File(uri.getPath());
                        return fromFile(file);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return uri;
    }

    public static Uri fromFile(File file) {
        Context context = MyApplication.applicationContext;
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = fromFileFor24(context, file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

    public static Uri fromFile(Context context, File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = fromFileFor24(context, file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

    public static final String FILE_PROVIDER_HOST = BuildConfig.APPLICATION_ID + ".fileprovider";

    private static Uri fromFileFor24(Context context, File file) {
        Uri fileUri = androidx.core.content.FileProvider.getUriForFile(context,
                FILE_PROVIDER_HOST,
                file);
        return fileUri;
    }

    public static void setIntentForCameraCrop(Intent intent) {
        if (Build.VERSION.SDK_INT >= 24) {
            Uri output = null;
            try {
                output = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
            } catch (ClassCastException e) {
            }
            if (output != null) {
                intent.setClipData(ClipData.newRawUri("", output));
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
        }
    }

    @Permissions(value = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, continueAfterGranted = true)
    public static void getFromCamera(Fragment fragment, File output) {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.getUriFromFile(fragment.getContext(), output));
            fragment.startActivityForResult(intent, ACTION_FROM_CAMERA);
        } catch (Exception e) {
            Toast.makeText(MyApplication.applicationContext, "此设备未开启照相权限或没有该功能", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Permissions(value = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, continueAfterGranted = true)
    public static void getFromCamera(Activity activity, File output) {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.getUriFromFile(activity, output));
            activity.startActivityForResult(intent, ACTION_FROM_CAMERA);
        } catch (Exception e) {
            Toast.makeText(MyApplication.applicationContext, "此设备未开启照相权限或没有该功能", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Permissions(value = {Manifest.permission.WRITE_EXTERNAL_STORAGE}, continueAfterGranted = true)
    public static void getFromPhotos(Fragment fragment) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);//Pick an item from the data
            intent.setType("image/*");//从所有图片中进行选择
            fragment.startActivityForResult(intent, ACTION_FROM_ALBUM);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Permissions(value = {Manifest.permission.WRITE_EXTERNAL_STORAGE}, continueAfterGranted = true)
    public static void getFromPhotos(Activity activity) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);//Pick an item from the data
            intent.setType("image/*");//从所有图片中进行选择
            activity.startActivityForResult(intent, ACTION_FROM_ALBUM);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 开始剪裁
     *
     * @param context
     * @param uri
     * @param size
     * @return 裁剪后的图片
     */
    public static File startCutPic(Activity context, Uri uri, int size) {
        File cutTempFile = FileUtils.createTempFile(System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("output", Uri.fromFile(cutTempFile));
        // crop为true是设置在开启的intent中设置显示的view可以剪裁

        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        if (Build.MANUFACTURER.contains("HUAWEI")) {// 华为特殊处理 不然会显示圆
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
            Log.d("super", "这个是华为手机----");
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            Log.d("super", "这个是LowB手机---");
        }
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        context.startActivityForResult(intent, ACTION_FROM_CROP);
        return cutTempFile;
    }

    /**
     * 开始剪裁
     *
     * @param uri
     * @param size
     * @return 裁剪后的图片
     */
    public static File startCutPic(Fragment fragment, Uri uri, int size) {
        File cutTempFile = FileUtils.createTempFile(System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("output", Uri.fromFile(cutTempFile));
        // crop为true是设置在开启的intent中设置显示的view可以剪裁

        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        if (Build.MANUFACTURER.contains("HUAWEI")) {// 华为特殊处理 不然会显示圆
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
            Log.d("super", "这个是华为手机----");
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        fragment.getActivity().startActivityFromFragment(fragment, intent, ACTION_FROM_CROP);
        return cutTempFile;
    }

    /**
     * 图片保存到媒体库种
     *
     * @param context
     * @param path
     * @return
     */
    public static Uri writeImageToContextProvider(Context context, String path, int height, int width) {
        if (context == null || TextUtils.isEmpty(path)) {
            return Uri.EMPTY;
        }

        //Log.d(CommonUtils.TAG, "writeImageToContextProvider path = " + path);

        ContentValues values = new ContentValues(4);
        values.put(MediaStore.Images.Media.DATA, path);

        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.WIDTH, width);
        values.put(MediaStore.Images.Media.HEIGHT, height);

        ContentResolver content = context.getContentResolver();

        String state = Environment.getExternalStorageState();

        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // Log.d(CommonUtils.TAG, "writeImageToContextProvider EXTERNAL_CONTENT_URI path = " + path);
            Uri uri = content.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                // Log.d(CommonUtils.TAG, "writeImageToContextProvider EXTERNAL_CONTENT_URI uri = " + uri.toString());
            }
            return uri;
        } else {
            //Log.d(CommonUtils.TAG, "writeImageToContextProvider INTERNAL_CONTENT_URI path = " + path);
            Uri uri = content.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
            return uri;
        }
    }
}
